function MiscUtils() {
};

MiscUtils.conjunction = 1;
MiscUtils.disjunction = 2;

/**
 * Generate a random string
 */
MiscUtils.unique = function() {
  var unique = 'u' + parseInt(new Date().getTime() * Math.random());
  unique = unique.replace('.', '');
  unique.substring(0, 16);
  return unique;
};

/**
 * 
 */
MiscUtils.digits = function(value, size) {
  var prefix = '';
  for (var i = 0, il = size - value.toString().length; i < il; i++) {
    prefix += '0';
  }
  return prefix + value;
};

/**
 * Copy an object
 */
MiscUtils.clone = function(object) {
  return JSON.parse(JSON.stringify(object));
};

/**
 * Display content input from text area in div
 */
MiscUtils.dispTextArea = function(content) {
  span = document.createElement('span');
  var str = '';
  for (var i = 0, il = content.length; i < il; i++) {
    if (content.charAt(i) != '\n') {
      str += content.charAt(i);
    } else {
      span.appendChild(document.createTextNode(str));
      span.appendChild(document.createElement('br'));
      str = '';
    }
  }
  span.appendChild(document.createTextNode(str));
  return span
};

/**
 * Display a customised dialog
 */
MiscUtils.dialog = function(popupBox, pos, content, func1, func2, options) {
  var table, tr, td, btn;
  if (options && options.pop) {
    table = document.createElement('table');
    table.cellPadding = 0;
    table.cellSpacing = 0;
    popupBox._open(table, { pos: pos, t: (options && options.t) ? options.t : '', width: (options && options.width) ? options.width : null, height: (options && options.height) ? options.height : null, pop: (options && options.pop) ? options.pop : null });
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.appendChild(content);
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.style.textAlign = 'center';
    if (func1 || func2) {
      if (func1) {
        btn = DOMUtils.createInput(null, null, 'button', (options && options.ok) ? options.ok : 'OK', null);
        btn.className = 'button';
        btn.onclick = func1;
        td.appendChild(btn);
      }
      if (func2) {
        btn = DOMUtils.createInput(null, null, 'button', (options && options.cancel) ? options.cancel : 'Cancel', null);
        btn.className = 'button';
        btn.onclick = func2;
        td.appendChild(btn);
      }
    }
  } else {
    table = document.createElement('table');
    popupBox._open(table, { pos: pos, t: (options && options.t) ? options.t : '', width: (options && options.width) ? options.width : null, height: (options && options.height) ? options.height : null, pop: (options && options.pop) ? options.pop : null, func: (options && options.func) ? options.func : null });
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.appendChild(content);
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.style.padding = '10px 0 2px 0';
    td.style.textAlign = 'center';
    if (func1 || func2) {
      if (func1) {
        btn = DOMUtils.createInput(null, null, 'button', (options && options.ok) ? options.ok : 'OK', null);
        btn.className = 'button';
        btn.style.marginBottom = '13px';
        btn.onclick = func1;
        td.appendChild(btn);
      }
      if (func2) {
        btn = DOMUtils.createInput(null, null, 'button', (options && options.cancel) ? options.cancel : 'Cancel', null);
        btn.className = 'button';
        btn.style.marginBottom = '13px';
        btn.onclick = func2;
        td.appendChild(btn);
      }
    }
  }
};

/**
 * Display a loading dialog
 */
MiscUtils.load = function(popupBox, pos, text) {
  var div = document.createElement('div');
  var img = document.createElement('img');
  img.src = 'image/loading.gif';
  img.style.margin = '0 0 5px 0';
  div.appendChild(img);
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createTextNode(text));
  div.style.margin = '0 0 5px 0';
  MiscUtils.dialog(popupBox, pos, div, null, null);
};

/**
 * Remove element(s) from an array by the specified attribute's value
 */
MiscUtils.remove = function(array, elem, attr) {
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    if ((!attr && elem.id == tmp.id) || (attr && elem[attr] == tmp[attr])) {
      array.splice(i, 1);
      break;
    }
  }
  return array;
};

/**
 * Sort an array objects by its attribute 'order' 
 */
MiscUtils.sortByOrder = function(array) {
  var array2 = [];
  for (var i = 0, il = array.length; i < il; i++) {
    var obj = array[i];
    
    if (array2.length != 0) {
      var is_added = false;
      for (var j = 0, jl = array2.length; j < jl; j++) {
        var obj2 = array2[j];
        if (parseFloat(obj.order, 10) < parseFloat(obj2.order, 10)) {
          array2.splice(j, 0, obj);
          is_added = true;
          j = array2.length;
        }
      }
      if (!is_added) {
        array2[array2.length] = obj;
      }
    } else {
      array2[array2.length] = obj;
    }
  }
  return array2;
};

/**
 * Return all the months
 */
MiscUtils.getMonths = function() {
  return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
};

/**
 * Return the month in words
 */
MiscUtils.getMonth = function(n) {
  var m = MiscUtils.getMonths();
  return m[n - 1];
};

/**
 * Return years (now - 50 years ago)
 */
MiscUtils.getYears = function() {
  var now = new Date().getYear() + 1900;
  var years = [];
  for (var i = now, il = now - 50; i > il; i--) {
    years[years.length] = i;
  }
  return years;
};

/**
 * Return all the months
 */
MiscUtils.formatDate = function(str, lang, noTime) {
  if (str == '0000-00-00 00:00:00') {
    return '-';
  }
  
  var tmp1 = str.split(' ');
  var tmp2 = tmp1[0].split('-');
  var tmp3 = tmp1[1].split(':');
  
  var year, month, day, hour, minute, second;
  year = tmp2[0];
  month = tmp2[1];
  day = tmp2[2];
  hour = tmp3[0];
  minute = tmp3[1];
  second = tmp3[2];
  
  if (lang == 'zh_CN' || lang == 'zh_TW') {
    if (!noTime) {
      return tmp1[0] + ' ' + hour + ':' + minute;
    } else {
      return tmp1[0];
    }
  } else if (lang == 'en') {
    if (!noTime) {
      return day + ' ' + MiscUtils.getMonth(month) + ' ' + year.substring(2, year.length) + ', ' + hour + ':' + minute;
    } else {
      return day + ' ' + MiscUtils.getMonth(month) + ' ' + year.substring(2, year.length);
    }
  }
  return lang;
};

/**
 * 
 */
MiscUtils.formatMoney = function(n_value) {
  //validate input
  if (isNaN(Number(n_value))) {
    return 'ERROR';
  }

  // save the sign
  var b_negative = Boolean(n_value < 0);
  n_value = Math.abs(n_value);

  // round to 1/100 precision, add ending zeroes if needed
  var s_result = String(Math.round(n_value * 1e2) % 1e2 + '00').substring(0, 2);

  // separate all orders
  var b_first = true;
  var s_subresult;
  while (n_value >= 1) {
    s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
    s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
    b_first = false;
    n_value = n_value / 1e3;
  }
  // add at least one integer digit
  if (b_first) {
    s_result = '0.' + s_result;
  }

  // apply formatting and return
  return b_negative ? '($' + s_result + ')' : '$' + s_result;
};

MiscUtils.toNumber = function(m_value) {
  return Number(m_value.replace(/[^0-9\.\-]+/g,""));
};

MiscUtils.getShortStr = function(str, len) {
  if (str.length < len) {
    return str;
  }
  
  var idx = str.lastIndexOf('.');
  var ext = str.substr(idx);
  
  if (ext.length > len) {
    return str.substr(0, len) + '...';
  } else {
    var remain = len - ext.length;
    if (remain % 2 != 0) {
      remain -= 1;
    }
    var left = str.substr(0, remain / 2);
    var right = str.substr(idx - remain / 2, remain / 2);
    return left + '...' + right + ext;
  }
};

MiscUtils.getShortName = function(str, len) {
  if (str.length < len) {
    return str;
  }
  
  var left = str.substr(0, len / 2);
  var right = str.substr(str.length - len / 2, str.length);
  return left + '...' + right;
};

MiscUtils.getShort = function(str, len) {
  if (str.length < len) {
    return str;
  }
  
  var left = str.substr(0, len);
  return left + '...';
};

MiscUtils.txt2span = function(content, rows) {
  var span = document.createElement('span');
  var str = '';
  for (var i = 0, il = content.length; i < il && rows > 0; i++) {
    if (content.charAt(i) != '\n') {
      str += content.charAt(i);
    } else {
      span.appendChild(document.createTextNode(str));
      span.appendChild(document.createElement('br'));
      str = '';
      rows--;
      if (rows <= 0 && i < il) {
        span.appendChild(document.createTextNode('...'));
      }
    }
  }
  span.appendChild(document.createTextNode(str));
  return span
};

MiscUtils.getSmallSize = function(actual, max) {
  var width = actual[0];
  var height = actual[1];
  var max_width = max[0];
  var max_height = max[1];
  if ((max_width && width > max_width) || (max_height && height > max_height)) {
    var RESIZEWIDTH = false;
    var RESIZEHEIGHT = false;
    if (max_width && width > max_width) {
      width_ratio = max_width / width;
      RESIZEWIDTH = true;
    }
    if (max_height && height > max_height) {
      height_ratio = max_height / height;
      RESIZEHEIGHT = true;
    }
    if (RESIZEWIDTH && RESIZEHEIGHT) {
      if (width_ratio < height_ratio) {
        $ratio = width_ratio;
      } else {
        $ratio = height_ratio;
      }
    } else if (RESIZEWIDTH) {
      $ratio = width_ratio;
    } else if (RESIZEHEIGHT) {
      $ratio = height_ratio;
    }
    return [parseInt(width * $ratio, 10), parseInt(height * $ratio, 10)];
  }
};
